package com.nl.deal;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nl.DealDataToSendMain;
import com.nl.util.Common;
import com.nl.util.ConfigUtils;



public final class Monitor {

	private static final Logger logger = LoggerFactory.getLogger(Monitor.class);
	private List<Thread> threadList;

	private static final int INTERVAL = Integer.parseInt(ConfigUtils.getInstance().getValue("interval"));

	private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

	private Monitor() {
		logger.info("Initialize Monitor.......");
	}

	private static class SingletonHolder {
		private static final Monitor instance = new Monitor();
	}

	public static Monitor getInstance() {
		return SingletonHolder.instance;
	}

	public void startMonitor() {
		this.service.scheduleAtFixedRate(new TargetTask(), INTERVAL * 60, INTERVAL * 60, TimeUnit.SECONDS);
	}

	public void setThreadList(List<Thread> threadList) {
		this.threadList = threadList;
	}

	private void exceute() {
		try {
			StringBuilder content = new StringBuilder();
			content.append(DealDataToSendMain.master + "主机,过滤进程未处理数据量:");
			if (DataCache.dealData.isEmpty()) {
				content.append("0;");
			} else{
				content.append(DataCache.dealData.size()+";");
			}
			int count = 0;
			for (Thread thread : threadList) {
				if (!thread.isAlive()) {
					count++;
					//thread.start();
					content.append("thread：").append(thread.getName());
					if (thread.isAlive()) {
						content.append("Abnormal status, startup successful;");
					} else {
						content.append("Abnormal status, startup failure;");
					}
				}
			}
			if(count == 0) {
				content.append(threadList.size() + "therad working");
			}
			logger.info(content.toString());
			Common.sendWarnSms(content.toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	private class TargetTask implements Runnable
	{
		public void run()
		{
			exceute();
			logger.info("send to msisdn");
		}		
	}
}


